<template>
  <component :is="useDrawer ? 'el-drawer' : 'el-dialog'"
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    :size="useDrawer ? '600px' : undefined"
    :width="useDrawer ? undefined : '600px'"
    @close="resetForm"
    destroy-on-close>

    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">

      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <Editor :value.sync="formData.content" />
      </el-form-item>

      <el-form-item label="排序" prop="sortOrder">
        <el-input-number v-model="formData.sortOrder" :min="0" />
      </el-form-item>

      <el-form-item label="状态" prop="enabled">
        <el-switch v-model="formData.enabled" />
      </el-form-item>

    </el-form>

    <div :slot="useDrawer ? 'default' : 'footer'" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </component>
</template>

<script>
import api from '@/common/api';

import Editor from '@/components/admin/Editor';

export default {
  name: 'EditSampleDialog',
  props: {
    useDrawer: {
      type: Boolean,
      default: false
    }
  },

  components: {
    Editor
  },

  data() {
    return {
      loading: false,
      dialogVisible: false,

      formData: {
        title: '',
        content: '',
        sortOrder: 0,
        enabled: true
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
        enabled: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.formData.id ? '编辑样例' : '添加样例'
    }
  },

  methods: {
    async open(data) {
      this.formData = Object.assign({}, this.formData, data)
      this.dialogVisible = true
    },

    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        title: '',
        content: '',
        sortOrder: 0,
        enabled: true
      }
    },

    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return

        try {
          this.loading = true
          const { data } = await api.admin_saveSample(this.formData)
          this.$message.success('保存成功')
          this.dialogVisible = false

          this.$emit('success', data.data)
        } finally {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 20px;
  text-align: right;
}
</style>